package controllers

import (
	"github.com/astaxie/beego"
	"beeblog/models"
	"fmt"
	"strings"
)

type TopicController struct {
	beego.Controller
}

func (this *TopicController) Get() {
	flag := checkAccount(this.Ctx)
	this.Data["IsLogin"] = flag
	this.Data["IsTopic"] = true
	var err error
	this.Data["Topics"], err = models.QureyAllTopics()
	if err != nil {
		beego.Error(err)
	}

	this.TplName = "topic.html"
}

func(this *TopicController)Post(){
	name := this.Input().Get("name")
	content := this.Input().Get("content")
	tid := this.Input().Get("tid")
	category := this.Input().Get("category")
	lables := this.Input().Get("lable")
	fmt.Println(name,content,tid)
	if len(tid) == 0{
		err := models.AddTopic(name,content,category,lables)
		if err != nil {
			beego.Error(err)
		}
	}else{
		err := models.UpdateTopic(tid,name,content,category,lables)
		if err != nil {
			beego.Error(err)
		}
	}

	this.Redirect("/topic", 302)
}

func (this *TopicController) Add() {
	if !checkAccount(this.Ctx) {
		this.Redirect("/login", 302)
		return
	}
	this.TplName = "topic_add.html"
}

func (this *TopicController) Modify(){
	if !checkAccount(this.Ctx) {
		this.Redirect("/login", 302)
		return
	}
	tid := this.Input().Get("tid")
	topic,err := models.QureyTopic(tid)
	if err!= nil{
		return
	}
	this.Data["Tid"] = tid
	this.Data["Topic"] = topic
	this.TplName = "topic_modify.html"
}

func (this *TopicController) Delete()  {
	if !checkAccount(this.Ctx) {
		this.Redirect("/login", 302)
		return
	}
	tid := this.Input().Get("tid")
	category := this.Input().Get("category")
	err := models.DeleteTopic(tid,category)
	if err!=nil{
		beego.Error(err)
	}
	this.Redirect("/topic",302)
}

func (this *TopicController) View(){
	flag := checkAccount(this.Ctx)
	this.Data["IsLogin"] = flag
	tid := this.Ctx.Input.Params()["0"]
	topic,err := models.QureyTopic(tid)
	if err!= nil{
		return
	}
	this.Data["Topic"] = topic
	this.Data["Lables"] = strings.Split(topic.Lables," ")
	this.TplName = "topic_view.html"

	replys,err := models.GetAllReply(tid)
	if err!= nil{
		return
	}
	this.Data["Replies"] = replys

}


